<template>
  <div class="product-share">
    <canvas type="2d" id="myCanvas" :hidden="false"></canvas>
  </div>
</template>

<script>
var canvas;
import { mapState } from "vuex";
export default {
  props: {
    shareInfo: Object,
    qrCodeUrl: String
  },
  components: {},
  data() {
    return {
      sharePath: "",
      shareCode: "",
      posterBg:
        "https://media.wxcwy.com/images/yqhy-bkt.png"
    };
  },
  watch: {
    "shareInfo.qrCodeUrl"() {
      this.getCavas();
    }
  },
  computed: {
    ...mapState(["userInfo"]),
    tipsText() {
      let amount = this.shareInfo.share_amount;
      return amount > 0
        ? ["加入美时汇", `您的好友将获得${amount}个币`]
        : ["来跟我一起", "玩转美粉币吧"];
    }
  },
  created() {
    this.$nextTick(() => {});
  },
  methods: {
    getCavas() {
      const query = wx.createSelectorQuery().in(this);
      query
        .select("#myCanvas")
        .fields({ node: true, size: true })
        .exec(res => {
          canvas = res[0].node;
          const ctx = canvas.getContext("2d");
          const { pixelRatio, screenWidth } = wx.getSystemInfoSync();
          const dpr = 2;
          canvas.width = res[0].width * dpr;
          canvas.height = res[0].height * dpr;
          ctx.scale(dpr, dpr);
          //绘制背景色
          ctx.fillStyle = "#fff";
          ctx.fillRect(0, 0, screenWidth, canvas.height);

          //绘制内容
          this.toDrawCanvas(ctx, screenWidth, canvas.height / dpr);
        });
    },
    async toDrawCanvas(ctx, imgW, imgH) {
      const posterImg = await this.loadImage(this.posterBg);

      ctx.drawImage(posterImg, 0, 0, imgW, imgH);
      this.toDrawQrCode(ctx, imgW);
      this.toDrawText(ctx, imgW);
    },
    async toDrawQrCode(ctx, screenWidth) {
      const qrCodeImg = await this.loadImage(this.shareInfo.qrCodeUrl);
      const avatarImg = await this.loadImage(this.userInfo.avatar);
      const avatarImgW = uni.upx2px(126);
      ctx.drawImage(
        qrCodeImg,
        screenWidth / 2 - uni.upx2px(140),
        uni.upx2px(920),
        uni.upx2px(280),
        uni.upx2px(280)
      );

      ctx.save();
      ctx.beginPath(); //开始绘制
      ctx.arc(
        screenWidth / 2,
        uni.upx2px(1060),
        avatarImgW / 2,
        0,
        Math.PI * 2,
        false
      );
      ctx.clip();
      ctx.drawImage(
        avatarImg,
        screenWidth / 2 - avatarImgW / 2,
        uni.upx2px(1060) - avatarImgW / 2,
        avatarImgW,
        avatarImgW
      );
      ctx.restore();
    },
    toDrawText(ctx, screenWidth) {
      let num = this.shareInfo.user_total;
      const textW = ctx.measureText(num).width;
      ctx.textAlign = "center";
      ctx.font = `500 ${uni.upx2px(32)}px Arial`;
      ctx.fillStyle = "#d70002";
      ctx.fillText(
        this.tipsText[0],
        screenWidth / 2,
        uni.upx2px(480),
        screenWidth
      );
      ctx.fillText(
        this.tipsText[1],
        screenWidth / 2,
        uni.upx2px(530),
        screenWidth
      );
      ctx.fillStyle = "#fff";
      ctx.font = `${uni.upx2px(32)}px Arial`;
      ctx.fillText(
        "已经成功邀请",
        screenWidth / 2 - uni.upx2px(60) - textW,
        uni.upx2px(650),
        screenWidth
      );
      ctx.fillText(
        "位好友",
        screenWidth / 2 + uni.upx2px(100) + textW,
        uni.upx2px(650),
        screenWidth
      );
      ctx.fillStyle = "#FDE403";
      ctx.font = `500 ${uni.upx2px(40)}px Arial`;
      ctx.fillText(
        num,
        screenWidth / 2 + uni.upx2px(44),
        uni.upx2px(650),
        screenWidth
      );
    },
    loadImage(url) {
      return new Promise((resolve, reject) => {
        let img = canvas.createImage();
        img.onload = () => resolve(img);
        img.onerror = reject;
        img.src = url;
      });
    },
    toSaveImage() {
      uni.canvasToTempFilePath(
        {
          canvas: canvas,
          fileType: "jpg",
          quality: 1,
          success: res => {
            this.sharePath = res.tempFilePath;
            this.saveImageToPhotosAlbum(res.tempFilePath);
            console.log(res.tempFilePath);
          },
          fail(err) {
            console.log(err);
            uni.showToast({
              icon: "none",
              title: "保存失败"
            });
          }
        },
        this
      );
    },
    saveImageToPhotosAlbum(path) {
      uni.saveImageToPhotosAlbum({
        filePath: path,
        success: () => {
          uni.showToast({
            title: "图片已经保存到相册\n快去分享吧",
            duration: 3000,
            icon: "none"
          });
          this.show = false;
        },
        fail: () => {
          wx.getSetting({
            success: res => {
              if (!res.authSetting["scope.writePhotosAlbum"]) {
                uni.showModal({
                  title: "保存失败",
                  content: "请同意访问您的相册",
                  success: res => {
                    if (res.confirm) {
                      wx.openSetting();
                    } else if (res.cancel) {
                      this.show = false;
                    }
                  }
                });
              }
            }
          });
        }
      });
    }
  }
};
</script>

<style lang="scss">
.product-share {
  canvas {
    position: fixed;
    left: -100000px;
    top: -10000px;
    width: 100%;
    height: 1448rpx;
  }
}
</style>
